


//
//  NNetworkClient.m
//  nncloud
//
//  Created by macfai on 2018/9/19.
//  Copyright © 2018年 youedata. All rights reserved.
//

#import "NNetworkClient.h"
#import "NN_API.h"
#import "NSString+MD5.h"
#import "NN_HTTPServer.h"


static  NSString *GETMethod = @"get";
static NSString *netFailTips = @"亲,您的网络开小差了";
#define kTimeout 15

static  AFHTTPSessionManager *manager;

@interface NNetworkClient()
{
    NSURLSessionDownloadTask *_downloadTask;
}

//@property(nonatomic,copy)NSString *channel;


@end


@implementation NNetworkClient


/**
 *  对AFHTTPSessionManager启用单例模式
 *
 *  @return 单例
 */
+ (AFHTTPSessionManager*)sharedManager{
    
    static NNetworkClient* sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc]init];
        manager = [AFHTTPSessionManager manager];
        //申明返回的结果是json类型
        manager.responseSerializer = [AFJSONResponseSerializer serializer];
        
        //***************************************************
        //这个是个很关键的地方
        //如果后台需要我们给他传json格式数据就这样传  测试中
//         manager.requestSerializer = [AFJSONRequestSerializer serializer];
        
        //***************************************************
        
        //正常的是这样传，直接用一个参数字典  一般是这样进行传递就可以了
        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        
        manager.requestSerializer.timeoutInterval = kTimeout;
//        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/javascript",@"application/json",@"text/html", nil];
        
    });
    return manager;
}
#pragma mark - get 请求

///get请求
+(void)getRequestWithBaseUrl:(NSString *)url setParameters:(NSDictionary *)paraDic success:(void (^)(id))success fail:(void (^)(NSError *))fail delegater:(UIView *)view
{
    NSError *error;
    if (!url) {
        fail(error);
        return;
    }
    NSString *requestUrl = [NSString stringWithFormat:@"%@%@",HTTP_BASE,url];
    YYLog(@"打印当前接口%@",requestUrl);
    [self getRequestWithUrl:requestUrl setParameters:paraDic success:^(id responseObject) {
        if (success) {
            success(responseObject);
        }
    } fail:^(NSError *error) {
        fail(error);
    } delegater:view];
    
}

///被基类方法调用
+(void)getRequestWithUrl:(NSString *)url setParameters:(NSDictionary *)paraDic success:(void (^)(id))success fail:(void (^)(NSError *))fail delegater:(UIView *)view
{
    
    if (view) {
        //        [MBProgressHUD showHUDAddedTo:view animated:YES];
//        [SVProgressHUD show];
    }
    
    AFHTTPSessionManager *manager = [self sharedManager];

    
///经过测试，请求时候AFHTTPRequestSerializer  这个可以不设置，应该是afnet直接帮助做了默认设置，
//    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
//    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    manager.requestSerializer.timeoutInterval = kTimeout;
    
    ///设置了这个就可以不设置105行的那句代码  所以get请求时 af 的设置项更少更简单
    
    ///进行get请求可以少设置很多东西，post  数据提交默认的格式时  url 编码
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/javascript",@"application/json",@"text/html", nil];
    
    //如果有内嵌证书的话需要这里选择其他模式
    AFSecurityPolicy * securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    
//    如果是需要验证自建证书，需要设置为YES
    securityPolicy.allowInvalidCertificates = YES;
    securityPolicy.validatesDomainName = NO;
    manager.securityPolicy = securityPolicy;
    [manager GET:url parameters:paraDic progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //因为是异步所以会延迟一下才显示出来
        if (success) {
            
            success(responseObject);
            //[MBProgressHUD hideHUDForView:view animated:YES];
//            [SVProgressHUD dismiss];
        }
        
//        YYLog(@"%@",responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        YYLog(@"fail");
        fail(error);
        if (view) {
            
            //    [MBProgressHUD hideHUDForView:view animated:YES];
//            [SVProgressHUD dismiss];
        }
    }];
    
}



#pragma mark - post 请求
///post请求  基类
+(void)postRequestWithBaseUrl:(NSString *)url setParameters:(NSDictionary *)paraDic success:(void (^)(id))success fail:(void (^)(NSError *))fail delegater:(UIView *)view
{
    NSError *error;
    if (!url) {
        fail(error);
        return;
    }
    
    NSString *requestUrl = [NSString stringWithFormat:@"%@%@",HTTP_BASE,url];
    
    [self postRequestWithUrl:requestUrl setParameters:paraDic success:^(id responseObject) {
        
        if ([responseObject isKindOfClass:[NSData class]]) {
            
            YYLog(@"%@",responseObject);
            //后台返回的是序列串  是json 序列串
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
            YYLog(@"8899%@",dict);
            
            if (success) {
                
                success(dict);
//                success(responseObject);
            }
            
        }else{
            
            if (success) {
                
                success(responseObject);
            }
        }
    } fail:^(NSError *error) {
        
        fail(error);
        YYLog(@"%@",error);
        
    } delegater:view];
    
}


///被基类方法调用
+(void)postRequestWithUrl:(NSString *)url setParameters:(NSDictionary *)paraDic success:(void (^)(id))success fail:(void (^)(NSError *))fail delegater:(UIView *)view
{
    
    if (view) {
        
    }
    //单例初始化一次，防止内存问题
//    AFHTTPSessionManager *manager = [self sharedManager];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    ///https://www.jianshu.com/p/0570837fcd79
    ///这个链接说明了一些问题或者参考AFNetworking 的github 官方关于三中编码方式的说明
    ///这个是一般请求的时候进行http 方式
    
    
    if ([NUserModel shareInstance].isDifferentRequest==YES) {
        
        ///提交个人大量数据时 采用了json 方式进行提交
        
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
        
    }else{
        
        //删除一条数据   和    注册时候用了post 接口方式
        //其实大多数时候post都是这种  url 编码 格式进行数据提交
        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        
    }
    
//    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

//    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    
    ///数据返回都使用json 格式返回  数据返回如果不指定 默认是这个
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    //application/x-www-form-urlencoded   post方式提交数据时进行url 编码  这应该是最常见的 POST 提交数据的方式,参见
    //四种常见的 POST 提交数据方式对应的content-type取值
    //https://www.cnblogs.com/wushifeng/p/6707248.html
    
//    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
    
    
    manager.requestSerializer.timeoutInterval = kTimeout;
    
    [manager POST:url parameters:paraDic progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (success) {
            
            success(responseObject);
            dispatch_async(dispatch_get_main_queue(), ^{
                //[SVProgressHUD dismiss];
                
            });
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        fail(error);
        if (view) {
            dispatch_async(dispatch_get_main_queue(), ^{
                //                [SVProgressHUD dismiss];
//                [PTSProgressHUD hide];
            });
        }
    }];
}


#pragma mark - 图片上传

//图片上传
+(void)uploadImage:(UIImage *)image url:(NSString *)urlString{
    
    NSString *requestUrl = [NSString stringWithFormat:@"%@%@",HTTP_BASE,urlString];
    
    AFHTTPSessionManager *manager = [self sharedManager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //上传图片/文字，POST
    
//    NSString *userId = [WDUserInfoModel shareInstance].memberId;
//
    //使用时需要把参数补齐
    NSDictionary *commanDic;
    
//    = @{@"ai.cc":CHANNEL,@"ai.cp":@"6C07A7D7C49F0E3FE692B5FF66715086",@"bi.ct":[ToolClass getIDFA],@"bi.dv":@"IOS",@"bi.mi":userId?userId:@""};
    
    NSDictionary *dic = [[NSMutableDictionary alloc]initWithDictionary:commanDic];
    
    
    [manager POST:requestUrl parameters:dic constructingBodyWithBlock:^(id  _Nonnull formData) {
        //对于图片进行压缩
        NSData *data = UIImageJPEGRepresentation(image, 0.1);
        //第一个代表文件转换后data数据，第二个代表图片的名字，第三个代表图片放入文件夹的名字，第四个代表文件的类型
        [formData appendPartWithFileData:data name:@"1" fileName:@"image.jpg" mimeType:@"image/jpg"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        YYLog(@"uploadProgress = %@",uploadProgress);
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary * obj = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        YYLog(@"%@",obj);
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        YYLog(@"error = %@",error);
    }];
}


///文件方式上传图片

+(void)uploadImage:(NSArray *)photos url:(NSString *)urlString parameters:(NSDictionary *)paraDic success:(void (^)(id))success fail:(void (^)(NSError *))fail delegater:(UIView *)view{
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.requestSerializer= [AFHTTPRequestSerializer serializer];
        manager.responseSerializer.acceptableContentTypes = [NSSet
                                                             setWithObjects:@"application/json",
                                                             @"text/html",
                                                             @"image/jpeg",
                                                             @"image/png",
                                                             @"application/octet-stream",
                                                             @"text/json",
                                                             nil];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        YYLog(@"%@",photos);
        [manager POST:urlString parameters:paraDic constructingBodyWithBlock:^(id  _Nonnull formData) {
            
            //对于图片进行压缩
            //        NSData *data = UIImageJPEGRepresentation(image, 0.1);
            //第一个代表文件转换后data数据，第二个代表图片的名字，第三个代表图片放入文件夹的名字，第四个代表文件的类型
            //        [formData appendPartWithFileData:data name:@"1" fileName:@"image.jpg" mimeType:@"image/jpg"];
            for (int i = 0; i < photos.count; i++) {
                NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
                formatter.dateFormat=@"yyyyMMddHHmmss";
                NSString *str=[formatter stringFromDate:[NSDate date]];
                NSString *fileName=[NSString stringWithFormat:@"%@.jpg",str];
                UIImage *image = photos[i];
                NSData *imageData = UIImageJPEGRepresentation(image, 0.28);
                //后台规定名称必须是file
                [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/jpg"];
                
            }
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            
            YYLog(@"uploadProgress = %@",uploadProgress);
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            NSDictionary * obj = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
            YYLog(@"%@",obj);
            success(obj);
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            YYLog(@"error = %@",error);
            
        }];
    
}

+(NSInteger)getStatusCodeWithObj:(NSDictionary *)dic{
    NSString *code = dic[@"code"];
    return [code integerValue];
}





@end
